package com.soft.small.host.service;

import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.soft.small.host.entity.HostClient;
import com.soft.small.util.encrypt.SignUtil;
import lombok.extern.slf4j.Slf4j;
import org.eclipse.paho.client.mqttv3.MqttConnectOptions;

@Slf4j
public class MqttConnect extends BaseService{
    private HostClient hostClient;
    private final static String model = "mqttConnect";

    public MqttConnect(HostClient hostClient) {
        this.hostClient = hostClient;
        setOptions();
    }

    public String getHTCTopic(String type){
        return getHTCTopic(hostClient.getSn(),model,type);
    }


    public void setOptions(){
        MqttConnectOptions options = new MqttConnectOptions();
        options.setMqttVersion(3);
        options.setUserName(hostClient.getUsername());
        options.setPassword(hostClient.getPassword().toCharArray());
        options.setConnectionTimeout(10);
        options.setKeepAliveInterval(300);
        options.setMaxReconnectDelay(5);
        options.setCleanSession(true);
        options.setAutomaticReconnect(true);
        //设置遗嘱
        String willTopic = getHTCTopic("hostLineState");
        options.setWill(willTopic,getWillData(),1,true);
        hostClient.setOptions(options);
    }

    public byte[] getWillData(){
        String lineState = "{\"sn\":\"\",\"lineState\":\"\"}";
        JSONObject lineStateJson = JSONUtil.parseObj(lineState);
        lineStateJson.put("sn",hostClient.getSn());
        lineStateJson.put("lineState","offline");
        String willMsg = getSendData(hostClient,lineStateJson.toString());
        byte[] willMsgByte = SignUtil.getPublishMessage(willMsg,hostClient.getMyMqttClient().getAppSecret());
        return willMsgByte;
    }

    public void hostOnline(){
        String data = "{ \"sn\": \"\", \"oemFirm\": \"0X8001\", \"hostType\": \"sn_small\", \"hostVersion\": \"V5.01.001\", \"modelVersion\": \"V1.01.188\", \"zigbeeHardwareVersion\": \"V5.39\", \"zigbeeSoftwareVersion\": \"V5.39\", \"hostLanIp\": \"192.168.1.19\", \"hostLanPort\": 1883, \"orderVersion\": \"V1.01.103\" }";
        JSONObject dataJson = JSONUtil.parseObj(data);
        dataJson.put("sn",hostClient.getSn());
        publishToCloud(hostClient,model,"hostOnline",dataJson.toString());
    }

    public void hostLineState(){
        String lineState = "{\"sn\":\"\",\"lineState\":\"\"}";
        JSONObject lineStateJson = JSONUtil.parseObj(lineState);
        lineStateJson.put("sn",hostClient.getSn());
        lineStateJson.put("lineState","online");
        publishToCloud(hostClient,model,"hostLineState",lineStateJson.toString());
    }
}
